﻿using LeonardoNews.Data;
using LeonardoNews.Models;
using LeonardoNews.Server.Models;
using LeonardoNews.Server.Repositories;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace LeonardoNews.Server.Controllers
{
    public class CommentsController : ApiController
    {
        private readonly CommentsRepository data;

        public CommentsController(CommentsRepository data)
        {
            this.data = data;
        }

        public CommentsController()
        {
            this.data = new CommentsRepository(new NewsContext());
        }

        public HttpResponseMessage Get(int id)
        {
            Comment comment = this.data.All().FirstOrDefault(x => x.ID == id);
            if (comment == null)
            {
                return this.Request.CreateErrorResponse(HttpStatusCode.NotFound, "Item not found!");
            }

            return this.Request.CreateResponse(HttpStatusCode.OK, comment);
        }

        public IEnumerable<CommentModel> Get()
        {
            List<Comment> comments = this.data.All().ToList();

            List<CommentModel> cm = new List<CommentModel>();
            foreach (var comment in comments)
            {
                cm.Add(new CommentModel()
                {
                    ID = comment.ID,
                    Article = ArticleModel.FromArticle(comment.Article),
                    ParentComment = comment.ParentComment,
                    Text = comment.Text,
                    User = comment.User
                });
            }
            return cm;
        }

        public HttpResponseMessage Post([FromBody]Comment value)
        {
            var post = value;
            this.data.Add(post);

            var message = this.Request.CreateResponse(HttpStatusCode.Created);
            message.Headers.Location = new Uri(this.Request.RequestUri + post.ID.ToString(CultureInfo.InvariantCulture));
            return message;
        }

        public void Delete(int id)
        {
            Comment comment = this.data.Get(id);
            var children = this.data.All().Where(c => c.ParentComment.ID == id).ToList();
            if (children == null || children.Count == 0)
            {
                this.data.Delete(comment);
                return;
            }
            else
            {
                foreach (var childComment in children)
                {
                    Delete(childComment.ID);
                }

                this.data.Delete(comment);
            }
        }
    }
}
